import 'dart:async';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jicaimao_flutter/entity/loginbean.dart';
import 'package:jicaimao_flutter/event/register_event.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/event_bus.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/string_utils.dart';
import 'package:jicaimao_flutter/views/mine/register_confirm_page.dart';
import 'package:jicaimao_flutter/views/web_page.dart';
import 'package:jicaimao_flutter/widget/app_bar.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final phone_controller = TextEditingController();
  final code_controller = TextEditingController();
  bool isClearshow = false;
  String codeMsg = "获取验证码";
  bool isGoReg = false;
  bool isCheck = false;
  bool isClickGetCode = false;
  EventBus eventBus = new EventBus();


  /// 倒计时的秒数，默认60秒。
  final int countdown = 60;

  /// 倒计时的计时器。
  Timer _timer;

  /// 当前倒计时的秒数。
  int _seconds;

  /// 当前墨水瓶（`InkWell`）的文本。
  String _verifyStr = '获取验证码';

  StreamSubscription listen;
  _RegisterPageState(){
    listen = eventBus.on<RegisterEvent>().listen((event) {
      // All events are of type UserLoggedInEvent (or subtypes of it).
      Navigator.pop(context);
    });
  }



 ///注册

  _register() {
    String pNum = phone_controller.text;
    String ver = code_controller.text;
    if(pNum.isEmpty){
     showToast( "请输入手机号码");
      return;
    }
    if(!RegexUtil.isMobileExact(pNum)){
      showToast( "手机号格式不正确");
      return;
    }
    if(!isClickGetCode){
      showToast( "请先获取验证码");
      return;
    }
    if (ver.isEmpty) {
      showToast("请输入验证码");
      return;
    }
    if(!isCheck){
      showToast( "请选择同意用户协议");
      return;
    }
    checkCode(pNum,ver);
  }


/// 获取验证码

  _getCode() {
    String pNum2 = phone_controller.text;
    isClickGetCode = true;
    if (pNum2.isEmpty) {
      showToast( "请输入手机号码");
      return;
    }
    if (!RegexUtil.isMobileExact(pNum2)) {
      showToast( "手机号格式不正确");
      return;
    }
    sendCode(pNum2);
  }


///开启倒计时

  countDown() {
    _startTimer();
    _verifyStr = '${_seconds}s';
    setState(() {});
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        _seconds = countdown;
//            inkWellStyle = _availableStyle;
        setState(() {});
        return;
      }
      _seconds--;
      _verifyStr = '${_seconds}s';
      setState(() {});
      if (_seconds == 0) {
        _verifyStr = '重新获取';
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  void initState() {
    super.initState();
    _seconds = countdown;
  }


  ///请求验证码
  sendCode(String phone) async {
    var data = {
      'codeType': 1,
      "mobile": phone,
    };
    var respone = await HttpUtil().post(NetAddress.getCode, data: data);
    print(respone);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    showToast( loginBean.msg);
    if (loginBean.code == "200") {
      countDown();
    } else {}
  }

  ///检验验证码
  checkCode(String phoneNmu,String phoneCode) async{
    var data = {
      'mobile': phoneNmu,
      "verificationCode": phoneCode,
      "codeType":'1'
    };
    var respone = await HttpUtil().post(NetAddress.checkCode, data: data);
    print(respone);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    showToast( loginBean.msg);
    if (loginBean.code == "200") {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => RegisterConfirmPage(mobile:phoneNmu,verificationCode:phoneCode)),
      );
    } else {}
  }

  setBtnState(text) {
    String pNum = phone_controller.text;
    String ver = code_controller.text;

    if (pNum.isNotEmpty && RegexUtil.isMobileExact(pNum) && ver.isNotEmpty) {
      setState(() {
        isGoReg = true;
      });
    } else {
      setState(() {
        isGoReg = false;
      });
    }
  }

  _inputCode() {
    return Container(
      height: 40,
      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
      color: Color(0xfff7f7f7),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: TextField(
              onChanged: setBtnState,
              controller: code_controller,
              inputFormatters: [LengthLimitingTextInputFormatter(11)],
              maxLength: 11,
              maxLines: 1,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                  hasFloatingPlaceholder: false,
                  counterText: '',
                  border: InputBorder.none,
                  hintText: '请输入验证码',
                  disabledBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none),
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 16.0,
              ),
            ),
          ),
          InkWell(
            child: Text(
              '$_verifyStr',
              style: TextStyle(color: Color(0xff6aa9ff)),
            ),
            onTap: _seconds == countdown ? _getCode : null,
          )
        ],
      ),
    );
  }

  _inputPhone() {
    return Container(
        height: 40,
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        margin: EdgeInsets.fromLTRB(0, 40, 0, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                onChanged: (text) {
                  setBtnState(text);
                  setState(() {
                    isClearshow = text.length > 0;
                  });
                },
                controller: phone_controller,
                inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                maxLength: 11,
                maxLines: 1,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    counterText: '',
                    border: InputBorder.none,
                    hintText: '请输入手机号',
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                width: 40,
                height: 40,
                padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
                child: Image.asset(isClearshow ? 'images/icon_error.png' : ''),
              ),
              onTap: () {
                phone_controller.clear();
                setState(() {
                  isClearshow = !isClearshow;
                });
              },
            )
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffafafa),
      appBar: AppBarNormal("注册"),
      body: SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minHeight: 120.0,
            ),
            child: Container(
              margin: EdgeInsets.only(left: 20, right: 20),
              child: Column(
                children: <Widget>[
                  //logo
                  Container(
                    margin: EdgeInsets.only(top: 40),
                    height: 70,
                    child: Center(
                      child: Image.asset(
                        'images/icon.png',
                        width: 70,
                        height: 70,
                      ),
                    ),
                  ),

                  ///手机号
                  _inputPhone(),

                  ///分割线
                  Container(
                    height: 1,
                    color: Color(0xffDCDCDC),
                  ),

                  ///验证码
                  _inputCode(),

                  ///注册
                  GestureDetector(
                    onTap: _register,
                    child: Container(
                        margin: EdgeInsets.only(top: 40),
                        decoration: new BoxDecoration(
                            color: isGoReg ? Color(0xffad5afe) : Color(0xffD4d4d4),
                            borderRadius: BorderRadius.circular(3.0)),
                        alignment: Alignment.center,
                        height: 40,
                        width: double.infinity,
                        child: Text(
                          "注册",
                          style: TextStyle(color: Colors.white),
                        )),
                  ),

                  ///协议和条款
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: Row(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              isCheck = !isCheck;
                            });
                          },
                          child: Container(
                            color: Color(0xfffefefe),
                            padding: EdgeInsets.only(
                                top: 10, bottom: 10, right: 5, left: 5),
                            child: Image.asset(
                              isCheck
                                  ? "images/icon_check.png"
                                  : "images/icon_uncheck.png",
                              width: 15,
                              height: 15,
                            ),
                          ),
                        ),
                        Text("我已经阅读并同意"),
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => WebPage(
                                        "集财猫注册及服务协议", NetAddress.registrationAgreement)));
                          },
                          child: Text(
                            "《协议》",
                            style: TextStyle(color: Color(0xffad5afe)),
                          ),
                        ),
                        Text("和"),
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>
                                        WebPage("用户隐私条款", NetAddress.privacyClause)));
                          },
                          child: Text("《隐私条款》",
                              style: TextStyle(color: Color(0xffad5afe))),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          )),
    );
  }

  @override
  void dispose() {
    _cancelTimer();
    listen?.cancel();
    super.dispose();
  }

  void showToast(String tipMsg) {
    Fluttertoast.showToast(
        msg: tipMsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.black87,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
